package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.ImgUntilYS;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.mapper.SuprAuthMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.MONIYOUXIGEAPI;
import com.ruoyi.system.outto.goods.NEWYXGAPI;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class MONIYOUXIGEAPIImpl implements MONIYOUXIGEAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    InterAttrMapper interAttrMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "add", salePartner);
        Map<String, Object> result = new HashMap<>();
        String responses = "";

        try {
            URL url = new URL("https://www.youxige.com/tools/daishou/daishou_submit_ajax.ashx?action=release");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set up connection parameters
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // We are sending data
            connection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Origin", "http://www.youxige.com");
            connection.setRequestProperty("Referer", "http://www.youxige.com/release.aspx?cid=20");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36");
            connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            connection.setRequestProperty("Cookie", salePartner.getTwoOther());
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, Object> param : params.entrySet()) {
                if (postData.length() > 0) {
                    postData.append("&");
                }
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append("=");
                postData.append(URLEncoder.encode(param.getValue().toString(), "UTF-8"));
            }

            // Send the data
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");
            connection.getOutputStream().write(postDataBytes);

            // Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // Read the server response
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                responses = response.toString();
            }
        }catch (Exception e){

        }
        System.out.println(responses);
        log.info("游戏阁添加接口请求参数={}", JSONObject.toJSONString(params));
        log.info("游戏阁添加接口返回参数={}", responses);
        JSONObject resultJson = JSONObject.parseObject(responses);
        if (!Objects.isNull(resultJson)) {
            if (!"1".equals(resultJson.getString("status"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
                //查询商品ID
                String goodid = selGoods(goodsInfoAndAttrValueDto.getAccountNumber(),salePartner);
                if(StringUtils.isNotEmpty(goodid)){
                    result.put("outId", goodid);
                }
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "添加失败");
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", responses);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        //先下架
        AjaxResult ajaxResult = delGame(goodsInfoAndAttrValueDto, salePartner);
        Integer code = JSONObject.parseObject(JSONObject.toJSONString(ajaxResult.get("data"))).getInteger("code");
        if(code==200) {
            //再新增
            return addGame(goodsInfoAndAttrValueDto, salePartner);
        }
        return AjaxResult.success(code);
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String type, SalePartner salePartner) {
        Map<String, Object> params = new HashMap<>();
        String substring = salePartner.getSaleName();
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        if(StringUtils.isEmpty(interAttr.getInterGameId())){
            throw new GlobalException("该游戏属性暂未匹配!!!"+goodsInfoAndAttrValueDto.getGameName());
        }
        params.put("cid", interAttr.getInterGameId());
        //区服
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
        params.put("ds_score", 0);
        builderRadioAttr(goodsInfoAndAttrValueDto,interAttr.getRadioAttr(),params);

        params.put("title", goodsInfoAndAttrValueDto.getTitle());
        params.put("kj", 1);
        params.put("account", goodsInfoAndAttrValueDto.getAccountNumber());
        String yxNameSx = "";
        if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")){
            yxNameSx = "cfsygoods";
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")){
            yxNameSx = "lolgoods";
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")){
            yxNameSx = "lolsygoods";
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")){
            yxNameSx = "jccgoods";
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")){
            yxNameSx = "sjzxdgoods";
        }
        String photo = youxigeUp(goodsInfoAndAttrValueDto.getTitleImg(), yxNameSx,salePartner);
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        for(GoodsInfoImg goodsInfoImg1 : infoImgs){
            String s = youxigeUp(goodsInfoImg1.getImgUrl(), yxNameSx,salePartner);
            photo+=","+s;
        }
        params.put("photo", photo);
        JSONObject kz = new JSONObject();
        JSONArray filedlist = new JSONArray();
        JSONObject price = new JSONObject();
        price.put("name","sell_price");
        price.put("value",goodsInfoAndAttrValueDto.getPrice());
        price.put("control_type","single-text");
        filedlist.add(price);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, interAttr.getCheckAttr(),filedlist);
        kz.put("filedlist",filedlist);
        params.put("kz", kz);
        params.put("bp", 1);
        params.put("lxfs", salePartner.getSaleKey());
        params.put("weixin", salePartner.getSaleKey());
        params.put("qq", salePartner.getSaleKey());
        params.put("remark", goodsInfoAndAttrValueDto.getDes());
        params.put("is_uplad", 0);
        params.put("cname", yxNameSx);
        return params;
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String twoOther = salePartner.getTwoOther();
        String[] split = twoOther.split(";");
        String cookie = "";
        String time = String.valueOf(System.currentTimeMillis()/1000);
        for(String s : split){
            if(s.contains("Hm_lpvt")){
                String[] split1 = s.split("=");
                s = split1[0]+"="+time;
            }
            cookie+=";"+s;
        }
        cookie = cookie.substring(1);

        String substring = salePartner.getSaleName();
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        Map<String, Object> result = new HashMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        String response = HttpRequest.post("https://www.youxige.com/tools/daishou/daishou_submit_ajax.ashx?action=daishou_ope&pid="+artRecs.get(0).getOutid()+"&gid="+interAttr.getInterGameId()+"&etype=xj")
                .header("Accept" , "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .header("Accept-Language" , "zh-CN,zh;q=0.9")
                .header("Connection" , "keep-alive")
                .header("Cookie" , cookie)
                .header("Referer" , "http://www.youxige.com/myproduct.aspx?sid=8")
                .header("Upgrade-Insecure-Requests" , "1")
                .header("User-Agent" , "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36")
                .execute().body();

        log.info("游戏阁删除接口请求参数={}", JSONObject.toJSONString(artRecs.get(0).getOutid()));
        log.info("游戏阁删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!Objects.isNull(resultJson)) {
            if (!"1".equals(resultJson.getString("status"))) {
                result.put("code", 500);
            } else {
                result.put("code", 200);
            }
            result.put("msg", resultJson.getString("msg"));
        } else {
            result.put("code", 500);
            result.put("msg", "删除失败");
        }
        result.put("req", JSONObject.toJSONString(artRecs.get(0).getOutid()));
        result.put("res", response);

        return AjaxResult.success(result);
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr, Map<String, Object> params) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                JSONObject att = new JSONObject();
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            String id = object.getString("id");
                            if(id.contains("_")){
                                id = id.split("_")[1];
                            }
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId"))?j.getString("YdConfigId").contains(oneValue):"111".contains(oneValue)).collect(Collectors.toList());
                                if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String interConfigId2 = jsonObject2.getString("id");
//                                    att.put("fieldId", InterConfigId);
//                                    att.put("fieldValue", interConfigId2);
                                    params.put(id, interConfigId2);
                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            String id = object.getString("id");
            if(id.contains("_")){
                id = id.split("_")[1];
            }
            if(StringUtils.isNotEmpty(id)) {
                interRadioReqs = object.getString("interRadioReqs");
                jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
                for (JSONObject objects : jsonObjects) {
                    if (StringUtils.isNotEmpty(objects.getString("defaultValue"))) {
//                        att.put("fieldId", id);
//                        att.put("fieldValue", objects.getString("id"));
                        params.put(id, objects.getString("id"));
                    }
                }
            }
        }
        //========================单选属性匹配结束=====================//
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String checkAttr, JSONArray valueList) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            JSONObject attr = new JSONObject();
            String pf_ids = "";
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {

                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

//                        List<String> list2 = new ArrayList<>();
//                        for (String s : split2) {
//                            s = s.replace(" ", "");
//                            list2.add(s);
//                        }
                        Object o = null;
                        try {
                            o = declaredField.get(goodsInfoAndAttrValueDto);
                        } catch (IllegalAccessException e) {
                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                        }
                        String oneValue = String.valueOf(o);
                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                        //开始匹配二级属性
                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                        /**
                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                         */
                        for (JSONObject jsonObject1 : jsonObjects2) {
                            String[] split1 = oneValue.split(",");
                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
                            for (String s : split1) {
                                if (Objects.equals(s, ydConfigId1)) {
                                    String InterConfigId2 = jsonObject1.getString("id");
                                    pf_ids+=","+InterConfigId2;
                                }
                            }
                        }

                    }
                }
            }
            if (StringUtils.isNotEmpty(pf_ids)) {
                attr.put("name", object.getString("id"));
                attr.put("value", pf_ids.substring(1).trim());
                attr.put("control_type", "multi-checkbox");
                valueList.add(attr);
            }
        }
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject.getString("interServeReqs");
        String qufuid = "";
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (qufuid.contains(ydServeId)) {
                        params.put("q_id", object.getString("id"));
                    }
                }
            }
        } else {
            qufuid = goodsInfoAndAttrValueDto.getGroupId() + "";
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (Objects.equals(qufuid, ydServeId)) {
                    params.put("q_id" , object.getString("id"));
                    String interServerRes = object.getString("interServerRes");
                    if(StringUtils.isNotEmpty(interServerRes)) {
                        List<JSONObject> twoServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                        for (JSONObject object2 : twoServer) {
                            String ydServeId2 = object2.getString("YdServeId");
                            qufuid = goodsInfoAndAttrValueDto.getServerId() + "";
                            if (qufuid.contains(ydServeId2)) {
                                params.put("s_id", object2.getString("id"));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        String[] split = "acw_tc=ab2ba99b17473888421227803ee96313ea09dcf13e857ed1848364a14f; cdn_sec_tc=ab2ba99b17473888421227803ee96313ea09dcf13e857ed1848364a14f; acw_sc__v2=682709aafd77a8c19126d0e8a25284b9a35ebd93; Hm_lvt_8ba4717310dcf202fa0c1fb02a53a570=1747388843; HMACCOUNT=BA92F80AA10A2FDD; Hm_lvt_ddd1dd7d74725efb31c09c4d77343558=1747388843; ASP.NET_SessionId=ouwpyfopgi3gowhvne340n5l; dt_cookie_user_name_remember=JFcms=18093522409; dt_cookie_user_pwd_remember=JFcms=BEB0B745AC0A078B9AB8FEE75985AE0B; Hm_lpvt_ddd1dd7d74725efb31c09c4d77343558=1747388851;Hm_lpvt_8ba4717310dcf202fa0c1fb02a53a570=1747388851".split(";");
        String cookie = "";
        String time = String.valueOf(System.currentTimeMillis()/1000);
        for(String s : split){
            if(s.contains("Hm_lpvt")){
                String[] split1 = s.split("=");
                s = split1[0]+"="+time;
            }
            cookie+=";"+s;
        }
        cookie = cookie.substring(1);
        System.out.println(cookie);
    }

    public static String youxigeUp(String img,String yxNamesx,SalePartner salePartner) {
        String twoOther = salePartner.getTwoOther();
        String[] split = twoOther.split(";");
        String cookie = "";
        String time = String.valueOf(System.currentTimeMillis()/1000);
        for(String s : split){
            if(s.contains("Hm_lpvt")){
                String[] split1 = s.split("=");
                s = split1[0]+"="+time;
            }
            cookie+=";"+s;
        }
        cookie = cookie.substring(1);
        System.out.println(cookie);
        String string = DigestUtils.md5Hex(img);
        File file = null;
        try {
            URL url = new URL(img);
            BufferedImage image = ImageIO.read(url.openStream());
            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
            bytes = ImgUntilYS.compressPicForScale(bytes, 2048l);
            file = convert(bytes,string);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            String mulu = "";
            LocalDate currentDate = LocalDate.now();
            String yyyyMMdd = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            mulu = mulu+yxNamesx+"/"+yyyyMMdd+"/"+System.currentTimeMillis();

            // URL of the server endpoint
            URL url = new URL("https://www.youxige.com/tools/upload_ajax.ashx?action=UpLoadFile&selfupname=daishou/"+mulu+"&IsWater=1&IsThumbnail=1&DelFilePath=&id=WU_FILE_1&name=2c97e7c98e7f44f0018e9a1056942256.jpg&type=image%2Fjpeg&lastModifiedDate=Wed+Apr+03+2024+11%3A25%3A11+GMT%2B0800+(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)&size=713375");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set up connection parameters
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // Indicate that we will send data
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            connection.setRequestProperty("Content-Type", "image/jpeg");
            connection.setRequestProperty("Origin", "http://www.youxige.com");
            connection.setRequestProperty("Referer", "http://www.youxige.com/release.aspx?cid=20");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36");
            connection.setRequestProperty("Cookie", cookie);

            byte[] fileBytes = new byte[(int) file.length()];

            // Read the file into a byte array
            try (FileInputStream fis = new FileInputStream(file)) {
                fis.read(fileBytes);
            }

            // Send the file data in the request body
            try (OutputStream os = connection.getOutputStream()) {
                os.write(fileBytes);
                os.flush();
            }

            // Get the response code
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // Read the server response
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                String path = JSONObject.parseObject(response.toString()).getString("path");
                return path;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static File convert(byte[] byteArray, String s) throws IOException {
        File file = File.createTempFile(s.substring(0,13), ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }catch (Exception e){

        }
        return file;
    }

    static String selGoods(String account,SalePartner salePartner){
        String twoOther = salePartner.getTwoOther();
        String[] split = twoOther.split(";");
        String cookie = "";
        String time = String.valueOf(System.currentTimeMillis()/1000);
        for(String s : split){
            if(s.contains("Hm_lpvt")){
                String[] split1 = s.split("=");
                s = split1[0]+"="+time;
            }
            cookie+=";"+s;
        }
        cookie = cookie.substring(1);
        String body = HttpRequest.get("http://www.youxige.com/myproduct.aspx?sid=0&kw="+account)
                .header("Accept" , "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .header("Accept-Language" , "zh-CN,zh;q=0.9")
                .header("Connection" , "keep-alive")
                .header("Cookie" , cookie)
                .header("Referer" , "http://www.youxige.com/myproduct.aspx?sid=0")
                .header("Upgrade-Insecure-Requests" , "1")
                .header("User-Agent" , "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36")
                .execute().body();
        Document parse = Jsoup.parse(body);
        Elements span = parse.select("span");
        for(Element element : span){
            if(element.text().contains("商品编号")){
                return element.text().split("：")[1];
            }
        }
        return null;
    }
}
